{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## merge sort 归并排序"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def merge(left, right):\n",
    "    res=[]\n",
    "    i=j=0\n",
    "    while True:\n",
    "        if left[i]<=right[j]:\n",
    "            res.append(left[i])\n",
    "            i+=1\n",
    "            if i>=len(left):\n",
    "                res.extend(right[j:])\n",
    "                break\n",
    "        else:\n",
    "            res.append(right[j])\n",
    "            j+=1    \n",
    "            if j>=len(right):\n",
    "                res.extend(left[i:])\n",
    "                break\n",
    "    return res\n",
    "\n",
    "\n",
    "def merge_sort(lists):\n",
    "    if len(lists) <= 1:\n",
    "        return lists\n",
    "    middle = len(lists)//2\n",
    "    left = merge_sort(lists[:middle])\n",
    "    right = merge_sort(lists[middle:])\n",
    "    return merge(left, right)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## insert sort 插入排序"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[3, 5, 5, 6, 6, 7, 7, 8]"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "l=[4,5,1,6,2,7,3,8]\n",
    "def insert_sort(Data):\n",
    "    for i in range(1,len(Data)):\n",
    "        value=Data[i]\n",
    "        j=i-1\n",
    "        while j>-1:\n",
    "            if value<Data[j]:\n",
    "                Data[j+1]=Data[j]\n",
    "                j-=1\n",
    "            else:\n",
    "                break\n",
    "            j-=1\n",
    "        Data[j+1]=value\n",
    "    return Data\n",
    "insert_sort(l)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
